

using UnityEngine;

//下面的写法相当于模板，后面是对T类型的限制，T可以是GameManager
public abstract class SingletonManager<T>: MonoBehaviour where T: MonoBehaviour //T是继承MonoBehaviour的类
{
    protected virtual void Awake()
    {
        T[] managers = FindObjectsByType<T>(FindObjectsSortMode.None);
        if (managers.Length > 1)
        {
            //如果有多个GameManager,则销毁当前的GameManager
            Destroy(gameObject);
            return;
        }
    }

    public static T Get()
    {
        var tag = typeof(T).Name; //获取GameManager的标签
        GameObject managerObject = GameObject.FindWithTag(tag);
        if (managerObject != null)
        {
            // 如果找到了GameManager，则返回GameManager
            return managerObject.GetComponent<T>();
        }

        GameObject go = new(tag);
        go.tag = tag;
        return go.AddComponent<T>(); //如果没有找到GameManager，则创建一个新的GameManager
    }
}